from api import Detector
from PIL import Image
import numpy as np
import time
import cv2
import matplotlib.pyplot as plt
from skimage import data, exposure, img_as_float

# Initialize detector
detector = Detector(model_name='rapid',
                    weights_path='./weights/rapid_pL1_dark53_H1MWMK_mix_angle1024_Nov06_2000.ckpt')
#使用视频数据
#capture=cv2.VideoCapture("./video/MW-18Mar-1.avi")
#capture=cv2.VideoCapture("./video/MW-18Mar-18.avi")
# capture=cv2.VideoCapture("./video/MW-18Mar-18_320x240.3gp2")
capture=cv2.VideoCapture("./video/3.mp4")
# 设置内容
image_resize_scale = (1080,1080)
use_our_image = True     # 使用自己的视频时，需要将这个选项改成True
fps = 0.0

while(True):
    t1 = time.time()
    # 读取某一帧
    ref,frame=capture.read()
    img = np.uint8(frame)
    #img = exposure.adjust_gamma(img, 0.5)
    # 转变成Image
    frame = Image.fromarray(np.uint8(img))

    # 首先对图像进行裁剪和resize
    if use_our_image:
        #frame = frame.crop([169,40,1065,713])   # (left, upper, right, lower) 正常裁剪
        frame = frame.crop([350,100,1500,960])    # ()   3.mp4
        #frame = frame.crop([230, 60, 1100, 720])                        # 昆山参数
        #frame = frame.crop([200, 0, 1700, 1080])                         # 无锡参数
        frame = frame.resize(image_resize_scale, Image.ANTIALIAS)  # resize image with high-quality
    if False:
        plt.figure("dog")
        plt.imshow(frame)
        plt.show()     # 可以
        print(frame.size)
    # 进行检测,打算借助对单幅图像处理的函数进行

    #frame = np.array(frcnn.detect_image(frame))
    frame = np.array(detector.detect_one(pil_img=frame,
                        input_size=1024, conf_thres=0.3,
                        return_img=True))
    # RGBtoBGR满足opencv显示格式
    #frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
    fps  = ( fps + (1./(time.time()-t1)) ) / 2
    print("fps= %.2f"%(fps))
    frame = cv2.putText(frame, "fps= %.2f"%(fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    out_win = "video_full_screen"
    cv2.namedWindow(out_win, cv2.WINDOW_NORMAL)
    cv2.setWindowProperty(out_win, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
    cv2.imshow(out_win,frame)
    c= cv2.waitKey(1) & 0xff 
    if c==27:
        capture.release()
        break

